﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using CUWo.Common;
using System.Reflection;
using System.Windows.Threading;
using CUWo.App.Views;
using CUWo.App.CustomControl;
using CUWo.Common.WebHelper;
using CUWo.Common.StorageHelper;
using CUWo.Common.Entities;
using System.Text;
using CUWo.Common.WoInterfaceCommunication;

namespace CUWo.App.WoControls
{
    public partial class WoActiveControl : UserControl
    {
        private const int TIMER_INTERVAL = 8;//秒
        private DispatcherTimer refreshTimerPanoramaActive;
        private int currentSelectedIndexFromPanoramaActive = 0;
        private ActInf currentSelectedItemFromPanoramaActive = null;
        public WebViewPage navigatePopup { get; set; }


        public WoActiveControl()
        {
            InitializeComponent();
        }

        public void LoadData()
        {
            string mobileNumber = string.Empty;
            var romInfoString = IsolatedStorageHelper.Instance.ReadText(Keys.ROM_FILENAME);
            if (!string.IsNullOrWhiteSpace(romInfoString))
            {
                RomInfo romInfo = JSONHelper.Deserialize<RomInfo>(romInfoString);
                if (romInfo != null)
                {
                    mobileNumber = romInfo.Mobile;
                }
            }
            if (string.IsNullOrWhiteSpace(mobileNumber))
            {
                MessageToastManager.Show("未登录，请登录！", MessageToastLevel.Warn);
                return;
            }
            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.ActiveInfo().GetUrl(mobileNumber);
            LogHelper.LogInfo(requestUrl);
            //

            PopupProgressBar.OpenProgressBar();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultMessageActiveInfo activeInfo = JSONHelper.Deserialize<JsonResultMessageActiveInfo>(decryptStringResult);
                            if (activeInfo != null)
                            {
                                if (activeInfo.Msg != null)
                                {
                                    if (activeInfo.Msg.MessageErrors != null && activeInfo.Msg.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(activeInfo.Msg.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (activeInfo.Msg.MessageWarns != null && activeInfo.Msg.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(activeInfo.Msg.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (activeInfo.Msg.MessagePrompts != null && activeInfo.Msg.MessagePrompts.Count > 0)
                                        {
                                            BindData(activeInfo.ActInf);
                                        }
                                    }
                                }
                            }

                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }

        public void BindData(IList<ActInf> actInfos)
        {
            if (!(actInfos != null && actInfos.Count > 0))
            {
                return;
            }

            var items = new ObservableCollection<ActInf>(actInfos);
            if (!(items != null && items.Count > 0))
            {
                return;
            }

            this.panelActiveSelectedIndex.Children.Clear();
            this.panoramaActive.Items.Clear();
            bool IsSetDefaultedItem = true;
            for (int i = 0; i < items.Count; i++)
            {
                try
                {
                    ActInf item = items[i];
                    if (item == null)
                        continue;

                    Image imageFocus = new Image();
                    imageFocus.Width = 400;
                    imageFocus.Stretch = System.Windows.Media.Stretch.Uniform;
                    imageFocus.MouseLeftButtonDown += delegate(object sender, System.Windows.Input.MouseButtonEventArgs e)
                    {
                        this.StopRefreshTimerFromPanoramaActive();
                    };
                    imageFocus.MouseLeftButtonUp += delegate(object sender, System.Windows.Input.MouseButtonEventArgs e)
                    {
                        this.StartRefreshTimerFromPanoramaActive();
                    };
                    if (!(item.ActPicInf != null && !string.IsNullOrWhiteSpace(item.ActPicInf.Path)))
                    {
                        //用默认图片
                    }
                    else
                    {
                        BitmapImage bmp = new BitmapImage(new Uri(item.ActPicInf.Path, UriKind.RelativeOrAbsolute));
                        imageFocus.Tag = item;
                        imageFocus.Source = bmp;
                    }

                    PanoramaItem pi = new PanoramaItem();
                    //pi.Margin = new Thickness(-12, -36, 0, 0);
                    pi.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    pi.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    pi.BorderThickness = new Thickness(0, 0, 5, 0);
                    pi.Content = imageFocus;
                    pi.Tag = item;
                    pi.Tap += pi_Tap;
                    //
                    this.panoramaActive.Items.Add(pi);
                    //
                    Border border = new Border();
                    border.BorderThickness = new Thickness(1);
                    border.BorderBrush = new SolidColorBrush(Helper.HexToColor("#ffff8c00"));
                    border.Height = 12;
                    border.Width = 30;
                    border.Margin = new Thickness(8, 0, 0, 0);
                    border.DataContext = item;
                    if (IsSetDefaultedItem)
                    {
                        IsSetDefaultedItem = false;
                        border.Background = new SolidColorBrush(Helper.HexToColor("#ffbebebe"));
                        (this.panoramaActive.Items[i] as PanoramaItem).Visibility = Visibility.Collapsed;
                        this.panoramaActive.SetValue(Panorama.SelectedItemProperty, this.panoramaActive.Items[i]);
                        this.panoramaActive.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                        (this.panoramaActive.Items[i] as PanoramaItem).Visibility = Visibility.Visible;
                        //
                        this.currentSelectedItemFromPanoramaActive = item;
                        //
                        BindActiveInfo(this.currentSelectedItemFromPanoramaActive);
                    }
                    border.Tag = i;
                    border.Tap += border_Tap;
                    TextBlock txt = new TextBlock() { Text = (i + 1).ToString(), FontSize = 12, Margin = new Thickness(-10), FontFamily = new FontFamily("Microsoft Yahei"), VerticalAlignment = System.Windows.VerticalAlignment.Center, HorizontalAlignment = System.Windows.HorizontalAlignment.Center, Foreground = new SolidColorBrush(Helper.HexToColor("#ffff8c00")) };
                    border.Child = txt;
                    this.panelActiveSelectedIndex.Children.Add(border);
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
            //热点：默认选择第一项并开启大图的调度器
            this.StartRefreshTimerFromPanoramaActive();
        }

        void BindActiveInfo(ActInf item)
        {
            if (item != null)
            {
                //ObservableCollection<ActInf> actInfo = new ObservableCollection<ActInf>(new List<ActInf>() { item });
                //this.gridActiveInfo.DataContext = item;
                this.txtTitle.Text = item.ActNm;
                this.txtContent.Text = item.ActCon;
                this.txtDateTime.Text = this.DateTimeToAbstract(item.BgnDtTm, item.EndDtTm);
            }
        }

        void border_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Border border = sender as Border;
            if (border == null)
                return;
            ActInf item = border.DataContext as ActInf;
            if (item == null)
                return;
            int index = 0;
            if (border.Tag != null)
                int.TryParse(border.Tag.ToString(), out index);
            try
            {
                if (index <= 0)
                    index = 0;
                else if (index >= this.panoramaActive.Items.Count - 1)
                    index = this.panoramaActive.Items.Count - 1;
                this.panoramaActive.DefaultItem = this.panoramaActive.Items[index];
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        void pi_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.StopRefreshTimerFromPanoramaActive();
            try
            {
                this.currentSelectedItemFromPanoramaActive = ((sender as PanoramaItem).Tag) as ActInf;
                if (this.currentSelectedItemFromPanoramaActive != null && !string.IsNullOrWhiteSpace(this.currentSelectedItemFromPanoramaActive.Lnk))
                {
                    LogHelper.LogInfo(this.currentSelectedItemFromPanoramaActive.Lnk, this.GetType(), MethodBase.GetCurrentMethod());
                    this.navigatePopup = new WebViewPage(this.currentSelectedItemFromPanoramaActive.Lnk);
                }
                else
                {
                    LogHelper.LogInfo("未选中", this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
            }
            this.StartRefreshTimerFromPanoramaActive();
        }

        private void StartRefreshTimerFromPanoramaActive()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    if (this.refreshTimerPanoramaActive == null)
                    {
                        this.refreshTimerPanoramaActive = new DispatcherTimer();
                        this.refreshTimerPanoramaActive.Interval = new TimeSpan(0, 0, TIMER_INTERVAL);
                        this.refreshTimerPanoramaActive.Tick += refreshTimerSubjectSlideshowBig_Tick;
                    }
                    this.refreshTimerPanoramaActive.Start();
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                }
            });
        }

        private void StopRefreshTimerFromPanoramaActive()
        {
            if (this.refreshTimerPanoramaActive != null)
            {
                this.refreshTimerPanoramaActive.Stop();
                this.refreshTimerPanoramaActive = null;
            }
        }

        private void refreshTimerSubjectSlideshowBig_Tick(object sender, object e)
        {
            UpdateCurrentSelectedItemToPanoramaActive();
        }

        private void UpdateCurrentSelectedItemToPanoramaActive(Helper.GestureDirection gestureDirection = Helper.GestureDirection.FromLeftToRight)
        {
            this.StopRefreshTimerFromPanoramaActive();
            if (gestureDirection == CUWo.Common.Helper.GestureDirection.FromLeftToRight)
            {
                //右移(下一条)
                if (this.currentSelectedIndexFromPanoramaActive < 0)
                    this.currentSelectedIndexFromPanoramaActive = 0;
                else
                    this.currentSelectedIndexFromPanoramaActive++;
                if (this.currentSelectedIndexFromPanoramaActive >= this.panoramaActive.Items.Count)//重置
                    this.currentSelectedIndexFromPanoramaActive = 0;
            }
            else if (gestureDirection == CUWo.Common.Helper.GestureDirection.FromRightToLeft)
            {
                //左移（上一条）
                if (this.currentSelectedIndexFromPanoramaActive > 0)
                    this.currentSelectedIndexFromPanoramaActive--;
                else
                    this.currentSelectedIndexFromPanoramaActive = this.panoramaActive.Items.Count - 1;
            }
            if (this.panoramaActive.Items != null && this.panoramaActive.Items.Count > 0)
            {
                try
                {
                    this.currentSelectedItemFromPanoramaActive = (this.panoramaActive.Items[this.currentSelectedIndexFromPanoramaActive] as PanoramaItem).Tag as ActInf;
                    (this.panoramaActive.Items[this.currentSelectedIndexFromPanoramaActive] as PanoramaItem).Visibility = Visibility.Collapsed;
                    this.panoramaActive.SetValue(Panorama.SelectedItemProperty, this.panoramaActive.Items[this.currentSelectedIndexFromPanoramaActive]);
                    this.panoramaActive.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                    (this.panoramaActive.Items[this.currentSelectedIndexFromPanoramaActive] as PanoramaItem).Visibility = Visibility.Visible;
                    //
                    BindActiveInfo(this.currentSelectedItemFromPanoramaActive);
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                }
            }

            this.StartRefreshTimerFromPanoramaActive();
        }

        private void panoramaActive_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.StopRefreshTimerFromPanoramaActive();
            try
            {
                this.currentSelectedIndexFromPanoramaActive = this.panoramaActive.SelectedIndex;
                for (int i = 0; i < this.panelActiveSelectedIndex.Children.Count; i++)
                {
                    try
                    {
                        Border border = this.panelActiveSelectedIndex.Children[i] as Border;
                        if (border == null)
                            continue;
                        ActInf item = border.DataContext as ActInf;
                        if (item == null)
                            continue;
                        int index = 0;
                        if (border.Tag != null)
                            int.TryParse(border.Tag.ToString(), out index);
                        if (index <= 0)
                            index = 0;
                        else if (index >= this.panoramaActive.Items.Count - 1)
                            index = this.panoramaActive.Items.Count - 1;
                        if (this.panoramaActive.SelectedIndex == index)
                        {
                            border.Background = new SolidColorBrush(Helper.HexToColor("#ffbebebe"));
                            this.currentSelectedItemFromPanoramaActive = item;
                        }
                        else
                        {
                            border.Background = new SolidColorBrush(Colors.Transparent);
                        }
                    }
                    catch (Exception err)
                    {
                        LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
            }

            BindActiveInfo(this.currentSelectedItemFromPanoramaActive);
            this.StartRefreshTimerFromPanoramaActive();
        }














        string DateTimeToAbstract(string beginDateTime, string endDateTime)
        {
            var bdt = DateTime.ParseExact(beginDateTime, "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
            var edt = DateTime.ParseExact(endDateTime, "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
            return string.Concat(bdt.ToString("yyyy年MM月dd日"), "~", edt.ToString("yyyy年MM月dd日"));
        }

        private List<ActInf> LoadLocalData()
        {
            List<ActInf> results = new List<ActInf>();
            ActInf actInf1 = new ActInf();
            actInf1.ActPicInf = new ActPicInf()
            {
                Path = "/Images/tmp/active01.png",
                Height = 600,
                Width = 456
            };
            actInf1.ActNm = "天天跑酷";
            actInf1.BgnDtTm = "20141118080808";
            actInf1.EndDtTm = "20141121080808";
            actInf1.ActCon = "《天天跑酷》是一款无需联网即可运行的横版跑酷游戏。秉承《天天酷跑》、《旋风跑跑(Wind Runner)》等游戏的优点，并在难度和操作体验上加以改善。画面清新，风格酷炫可爱，4款多变场景让你体验从沙漠穿越到北极的爽快。";
            actInf1.Lnk = "http://www.baidu.com";

            ActInf actInf2 = new ActInf();
            actInf2.ActPicInf = new ActPicInf()
            {
                Path = "/Images/tmp/active02.png",
                Height = 600,
                Width = 456
            };
            actInf2.ActNm = "天天爱阅读";
            actInf2.BgnDtTm = "20141111080808";
            actInf2.EndDtTm = "20141118080808";
            actInf2.ActCon = "《天天爱阅读》定位于Windows Phone上最有价值的、最接地气的阅读器。";
            actInf2.Lnk = "http://www.baidu.com";

            ActInf actInf3 = new ActInf();
            actInf3.ActPicInf = new ActPicInf()
            {
                Path = "/Images/tmp/active03.png",
                Height = 600,
                Width = 456
            };
            actInf3.ActNm = "应用家";
            actInf3.BgnDtTm = "20141121080808";
            actInf3.EndDtTm = "20141128080808";
            actInf3.ActCon = "应用家》定位于Windows Phone上最有价值的、最接地气的应用商店。具有智能APP推荐和语音搜索等功能，不仅能让用户快速下载到自己想要的应用，而且通过独家的视频介绍帮助用户能够更加深入地了解推荐APP的内容及玩法，有效提高用户体验。";
            actInf3.Lnk = "http://www.baidu.com";
            //
            results.Add(actInf1);
            results.Add(actInf2);
            results.Add(actInf3);

            return results;
        }
    }
}
